package xdsysadmin2

import grails.transaction.Transactional
import initConfig.SysInitData
import org.apache.ibatis.io.Resources
import org.apache.ibatis.session.SqlSession
import org.apache.ibatis.session.SqlSessionFactory
import org.apache.ibatis.session.SqlSessionFactoryBuilder

@Transactional
class MyBatisUtilService {

    /**
     * 获取mybatis 配置
     * @return
     */
    public InputStream getMyBatisCfgInStream(){
        return Resources.getResourceAsStream(SysInitData.MybatisConfigXML)
    }

    public getSqlSessionFactory(){
        def inputStream = getMyBatisCfgInStream()
        return  new SqlSessionFactoryBuilder().build(inputStream);
    }
    /**
     * 根据mybatis-config.xml的环境名称创建
     * @param environment
     */
    public getSqlSessionFactory(environment){
        def inputStream  = getMyBatisCfgInStream()
        return  new SqlSessionFactoryBuilder().build(inputStream,environment);
    }

    /**
     * 获取sqlsession
     * @return
     */
    public SqlSession getSqlSession(){
        return getSqlSessionFactory().openSession()
    }

    public SqlSession getSqlSession(environment){
        return getSqlSessionFactory(environment).openSession()
    }

    /**
     *
     * @param sqlSessionFactory
     * @return
     */
    public commitSession(SqlSession session){
        try{
            session.commit()
        }catch (Exception e){
            session.rollback()
        }
    }

    public closeSession(SqlSession session){
        try{
            session.close()
            if(session){
                session = null
            }
        }catch (Exception e){

        }
    }

    /**
     * 提交并关闭session
     * @return
     */
    public commitAndCloseSession(SqlSession session){
        commitSession(session)
        closeSession(session)
    }
}
